package org.example.serviceoffice.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.model.manage.bean.po.Counselor;
import org.example.model.manage.bean.po.Faculty;
import org.example.model.manage.bean.po.Office;
import org.example.model.manage.bean.po.Major;
import org.example.model.manage.bean.po.Student;
import org.example.model.manage.bean.po.security.User;
import org.example.model.manage.bean.po.CounselorMajor;
import org.example.model.manage.bean.vo.FacultyCount;
import org.example.model.manage.bean.po.security.UserRole;
import org.example.model.manage.bean.vo.SchoolCount;
import org.example.model.manage.bean.vo.MajorCount;
import org.example.model.manage.bean.vo.MajorImportResult;
import org.example.serviceoffice.mapper.OfficeMapper;
import org.example.serviceoffice.mapper.CounselorMapper;
import org.example.serviceoffice.mapper.FacultyMapper;
import org.example.serviceoffice.mapper.UserMapper;
import org.example.serviceoffice.mapper.MajorMapper;
import org.example.serviceoffice.mapper.UserRoleMapper;
import org.example.serviceoffice.mapper.CounselorMajorMapper;
import org.example.serviceoffice.service.OfficeService;
import org.example.serviceoffice.service.OfficeStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.example.serviceoffice.vo.PageResult;
import org.example.serviceoffice.vo.StudentListVO;
import org.example.serviceoffice.vo.CounselorWithMajorVO;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

@Service
public class OfficeServiceImpl extends ServiceImpl<OfficeMapper, Office> implements OfficeService {

    @Autowired
    private OfficeMapper officeMapper;

    @Autowired
    private OfficeStudentService officeStudentService;

    @Autowired
    private CounselorMapper counselorMapper;

    @Autowired
    private FacultyMapper facultyMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MajorMapper majorMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private CounselorMajorMapper counselorMajorMapper;

    @Override
    public List<FacultyCount> getFacultyCounts() {
        // 查询所有学院统计信息
        List<FacultyCount> facultyCounts = officeMapper.selectAllFacultyCounts();
        
        // 计算每个学院的报到率、已报道人数和未报道人数
        for (FacultyCount facultyCount : facultyCounts) {
            Integer totalStudents = facultyCount.getTotalStudents();
            Integer reportedStudents = facultyCount.getReportedStudents();
            
            if (totalStudents != null && totalStudents > 0) {
                Double reportRate = (double) reportedStudents / totalStudents;
                facultyCount.setReportRate(reportRate);
            } else {
                facultyCount.setReportRate(0.0);
            }
            
            facultyCount.setReportNum(reportedStudents);
            facultyCount.setUnreportNum(totalStudents - reportedStudents);
            
            // 移除不再需要的字段
            facultyCount.setTotalStudents(null);
            facultyCount.setReportedStudents(null);
        }
        
        return facultyCounts;
    }



    @Override
    public SchoolCount getSchoolCount() {
        // 查询全校统计信息
        SchoolCount schoolCount = officeMapper.selectSchoolCount();
        
        if (schoolCount != null) {
            Integer totalStudents = schoolCount.getTotalStudents();
            Integer reportNum = schoolCount.getReportNum();
            
            // 计算未报道人数和报到率
            schoolCount.setUnreportNum(totalStudents - reportNum);
            
            if (totalStudents != null && totalStudents > 0) {
                Double reportRate = (double) reportNum / totalStudents;
                schoolCount.setReportRate(reportRate);
            } else {
                schoolCount.setReportRate(0.0);
            }
        }
        
        return schoolCount;
    }

    @Override
    public Student addStudent(Student student) {
        if (student == null) {
            throw new IllegalArgumentException("学生信息不能为空");
        }
        
        // 调用OfficeStudentService添加学生
        return officeStudentService.addStudent(student);
    }
    
    @Override
    public List<FacultyCount> getFacultyList() {
        // 查询所有学院列表
        return officeMapper.selectAllFacultyCounts();
    }
    
    @Override
    public List<MajorCount> getMajorReportListByFaculty(Integer facultyId) {
        // 查询指定学院各专业的报道统计信息
        List<MajorCount> majorCounts = officeMapper.selectMajorCountsByFacultyId(facultyId);
        
        // 计算每个专业的报到率、已报道人数和未报道人数
        for (MajorCount majorCount : majorCounts) {
            Integer totalStudents = majorCount.getTotalStudents();
            Integer reportedStudents = majorCount.getReportedStudents();
            
            if (totalStudents != null && totalStudents > 0) {
                Double reportRate = (double) reportedStudents / totalStudents;
                majorCount.setReportRate(reportRate);
            } else {
                majorCount.setReportRate(0.0);
            }
            
            majorCount.setReportNum(reportedStudents);
            majorCount.setUnReportNum(totalStudents - reportedStudents);
            
            // 移除不再需要的字段
            majorCount.setTotalStudents(null);
            majorCount.setReportedStudents(null);
        }
        
        return majorCounts;
    }



    @Override
    public Faculty getFacultyByName(String name) {
        // 根据名称查找学院
        return facultyMapper.selectByName(name);
    }

    @Override
    public Faculty createFaculty(Faculty faculty) {
        // 创建学院
        facultyMapper.insertFaculty(faculty);
        return faculty;
    }

    @Override
    public Counselor getCounselorById(Integer id) {
        // 根据ID查找辅导员
        return counselorMapper.selectById(id);
    }

    @Override
    public Counselor createCounselor(Counselor counselor) {
        // 创建辅导员（数据库自增ID回填到 counselor.id）
        counselorMapper.insertCounselor(counselor);
        return counselor;
    }

    @Override
    public User createUser(User user) {
        // 创建用户
        userMapper.insertUser(user);
        // 为用户分配角色，role 与 user.type 一致
        Integer roleId = null;
        if ("office".equalsIgnoreCase(user.getType())) {
            roleId = 1;
        } else if ("faculty".equalsIgnoreCase(user.getType())) {
            roleId = 2;
        } else if ("counselor".equalsIgnoreCase(user.getType())) {
            roleId = 3;
        }
        if (roleId != null && user.getId() != null) {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(roleId);
            userRoleMapper.insertUserRole(userRole);
        }
        return user;
    }

    @Override
    public Faculty getFacultyById(Integer id) {
        // 根据ID查找学院
        return facultyMapper.selectById(id);
    }

    @Override
    public String importCounselorsFromCsv(MultipartFile file) {
        try {
            List<String> successList = new ArrayList<>();
            List<String> errorList = new ArrayList<>();
            int lineNumber = 1;

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
                
                String line;
                // 跳过标题行
                reader.readLine();
                lineNumber++;
                
                while ((line = reader.readLine()) != null) {
                    try {
                        String[] fields = line.split(",");
                        if (fields.length >= 3) {
                            String counselorId = fields[0].trim();
                            String counselorName = fields[1].trim();
                            String facultyName = fields[2].trim();
                            
                            // 检查学院是否存在
                            Faculty faculty = getFacultyByName(facultyName);
                            if (faculty == null) {
                                errorList.add("第" + lineNumber + "行: 学院名称 '" + facultyName + "' 不存在");
                                lineNumber++;
                                continue;
                            }
                            
                            // 检查辅导员是否已存在
                            Counselor existing = getCounselorById(Integer.parseInt(counselorId));
                            if (existing == null) {
                                // 创建新辅导员
                                Counselor newCounselor = new Counselor();
                                newCounselor.setId(Integer.parseInt(counselorId));
                                newCounselor.setName(counselorName);
                                newCounselor.setFaculty(facultyName);
                                createCounselor(newCounselor);

                                // 自动创建用户账号
                                User user = new User();
                                user.setAccount(counselorName);
                                user.setPassword(passwordEncoder.encode(counselorName));
                                user.setType("counselor");
                                user.setTypeId(Integer.parseInt(counselorId));
                                createUser(user);

                                successList.add("第" + lineNumber + "行: " + counselorName + " (学院: " + facultyName + ") 导入成功");
                            } else {
                                errorList.add("第" + lineNumber + "行: " + counselorName + " 已存在");
                            }
                        } else {
                            errorList.add("第" + lineNumber + "行: 数据格式错误，需要至少3个字段");
                        }
                    } catch (Exception e) {
                        errorList.add("第" + lineNumber + "行: " + e.getMessage());
                    }
                    lineNumber++;
                }
            }

            StringBuilder result = new StringBuilder();
            result.append("导入完成！\n");
            result.append("成功导入: ").append(successList.size()).append(" 条\n");
            result.append("失败: ").append(errorList.size()).append(" 条\n");
            
            if (!successList.isEmpty()) {
                result.append("\n成功列表:\n");
                successList.forEach(s -> result.append(s).append("\n"));
            }
            
            if (!errorList.isEmpty()) {
                result.append("\n失败列表:\n");
                errorList.forEach(s -> result.append(s).append("\n"));
            }

            return result.toString();
        } catch (IOException e) {
            throw new RuntimeException("读取CSV文件失败: " + e.getMessage());
        }
    }

    @Override
    public String importStudentsFromCsv(MultipartFile file) {
        try {
            List<String> successList = new ArrayList<>();
            List<String> errorList = new ArrayList<>();
            int lineNumber = 1;

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
                
                String line;
                // 跳过标题行
                reader.readLine();
                lineNumber++;
                
                while ((line = reader.readLine()) != null) {
                    try {
                        String[] fields = line.split(",");
                        if (fields.length >= 8) {
                            String studentId = fields[0].trim();
                            String studentName = fields[1].trim();
                            String majorId = fields[2].trim();
                            String className = fields[3].trim();
                            String telephone = fields[4].trim();
                            String reportCheck = fields[5].trim();
                            String dormitory = fields[6].trim();
                            String unionId = fields.length > 7 ? fields[7].trim() : "";
                            String pid = fields.length > 8 ? fields[8].trim() : "";

                            // 创建学生对象
                            Student student = new Student();
                            student.setId(Integer.parseInt(studentId));
                            student.setName(studentName);
                            student.setMajorId(Integer.parseInt(majorId));
                            student.setClassName(className);
                            student.setTelephone(telephone);
                            student.setReportCheck(Integer.parseInt(reportCheck));
                            student.setDormitory(dormitory);
                            student.setUnionId(unionId);
                            student.setPid(pid);

                            // 添加学生
                            Student savedStudent = addStudent(student);
                            successList.add("第" + lineNumber + "行: " + studentName + " 导入成功");

                        } else {
                            errorList.add("第" + lineNumber + "行: 数据格式错误，需要至少8个字段");
                        }
                    } catch (Exception e) {
                        errorList.add("第" + lineNumber + "行: " + e.getMessage());
                    }
                    lineNumber++;
                }
            }

            StringBuilder result = new StringBuilder();
            result.append("导入完成！\n");
            result.append("成功导入: ").append(successList.size()).append(" 条\n");
            result.append("失败: ").append(errorList.size()).append(" 条\n");
            
            if (!successList.isEmpty()) {
                result.append("\n成功列表:\n");
                successList.forEach(s -> result.append(s).append("\n"));
            }
            
            if (!errorList.isEmpty()) {
                result.append("\n失败列表:\n");
                errorList.forEach(s -> result.append(s).append("\n"));
            }

            return result.toString();
        } catch (IOException e) {
            throw new RuntimeException("读取CSV文件失败: " + e.getMessage());
        }
    }

    @Override
    public String importFacultiesFromCsv(MultipartFile file) {
        try {
            List<String> successList = new ArrayList<>();
            List<String> errorList = new ArrayList<>();
            int lineNumber = 1;

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
                
                String line;
                // 跳过标题行
                reader.readLine();
                lineNumber++;
                
                while ((line = reader.readLine()) != null) {
                    try {
                        String[] fields = line.split(",");
                        if (fields.length >= 1) {
                            String facultyName = fields[0].trim();
                            
                            if (facultyName.isEmpty()) {
                                errorList.add("第" + lineNumber + "行: 学院名称不能为空");
                                lineNumber++;
                                continue;
                            }
                            
                            // 检查学院是否已存在
                            Faculty existing = getFacultyByName(facultyName);
                            if (existing == null) {
                                // 创建新学院
                                Faculty newFaculty = new Faculty();
                                newFaculty.setFaculty(facultyName);
                                Faculty savedFaculty = createFaculty(newFaculty);

                                // 自动创建学院用户账号
                                User user = new User();
                                user.setAccount(facultyName);
                                user.setPassword(passwordEncoder.encode(facultyName));
                                user.setType("faculty");
                                user.setTypeId(savedFaculty.getId());
                                createUser(user);

                                successList.add("第" + lineNumber + "行: " + facultyName + " 导入成功");
                            } else {
                                errorList.add("第" + lineNumber + "行: " + facultyName + " 已存在");
                            }
                        } else {
                            errorList.add("第" + lineNumber + "行: 数据格式错误，需要至少1个字段");
                        }
                    } catch (Exception e) {
                        errorList.add("第" + lineNumber + "行: " + e.getMessage());
                    }
                    lineNumber++;
                }
            }

            StringBuilder result = new StringBuilder();
            result.append("导入完成！\n");
            result.append("成功导入: ").append(successList.size()).append(" 条\n");
            result.append("失败: ").append(errorList.size()).append(" 条\n");
            
            if (!successList.isEmpty()) {
                result.append("\n成功列表:\n");
                successList.forEach(s -> result.append(s).append("\n"));
            }
            
            if (!errorList.isEmpty()) {
                result.append("\n失败列表:\n");
                errorList.forEach(s -> result.append(s).append("\n"));
            }

            return result.toString();
        } catch (IOException e) {
            throw new RuntimeException("读取CSV文件失败: " + e.getMessage());
        }
    }

    @Override
    public MajorImportResult importMajorsFromCsv(MultipartFile file) {
        try {
            List<String> successList = new ArrayList<>();
            List<String> errorList = new ArrayList<>();
            List<String> nonExistentFaculties = new ArrayList<>();
            int lineNumber = 1;

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
                
                String line;
                // 跳过标题行
                reader.readLine();
                lineNumber++;
                
                while ((line = reader.readLine()) != null) {
                    try {
                        String[] fields = line.split(",");
                        if (fields.length >= 2) {
                            String majorName = fields[0].trim();
                            String facultyName = fields[1].trim();
                            
                            if (majorName.isEmpty()) {
                                errorList.add("第" + lineNumber + "行: 专业名称不能为空");
                                lineNumber++;
                                continue;
                            }
                            
                            if (facultyName.isEmpty()) {
                                errorList.add("第" + lineNumber + "行: 学院名称不能为空");
                                lineNumber++;
                                continue;
                            }
                            
                            // 根据学院名称查找学院
                            Faculty faculty = getFacultyByName(facultyName);
                            if (faculty == null) {
                                // 学院不存在，添加到列表中
                                if (!nonExistentFaculties.contains(facultyName)) {
                                    nonExistentFaculties.add(facultyName);
                                }
                                errorList.add("第" + lineNumber + "行: 学院名称 '" + facultyName + "' 不存在");
                                lineNumber++;
                                continue;
                            }
                            
                            // 检查专业是否已存在（基于名称和学院ID）
                            Major existingMajor = majorMapper.selectByNameAndFacultyId(majorName, faculty.getId());
                            if (existingMajor != null) {
                                errorList.add("第" + lineNumber + "行: 专业 '" + majorName + "' (学院: " + facultyName + ") 已存在");
                                lineNumber++;
                                continue;
                            }
                            
                            // 创建新专业
                            Major newMajor = new Major();
                            newMajor.setMajor(majorName);
                            newMajor.setFacultyId(faculty.getId());
                            majorMapper.insertMajor(newMajor);

                            successList.add("第" + lineNumber + "行: " + majorName + " (学院: " + facultyName + ") 导入成功");
                            
                        } else {
                            errorList.add("第" + lineNumber + "行: 数据格式错误，需要至少2个字段");
                        }
                    } catch (Exception e) {
                        errorList.add("第" + lineNumber + "行: " + e.getMessage());
                    }
                    lineNumber++;
                }
            }

            // 构建返回结果
            MajorImportResult result = new MajorImportResult();
            result.setMessage("导入完成！");
            result.setSuccessCount(successList.size());
            result.setErrorCount(errorList.size());
            result.setNonExistentFaculties(nonExistentFaculties);
            result.setSuccessList(successList);
            result.setErrorList(errorList);

            return result;
        } catch (IOException e) {
            throw new RuntimeException("读取CSV文件失败: " + e.getMessage());
        }
    }

    @Override
    public PageResult<Student> getStudentPage(int page, int size) {
        int p = Math.max(page, 1);
        int s = Math.max(size, 1);
        int offset = (p - 1) * s;
        List<Student> items = officeMapper.selectStudentsPaged(offset, s);
        long total = officeMapper.countStudents();
        PageResult<Student> result = new PageResult<>();
        result.setPage(p);
        result.setSize(s);
        result.setTotal(total);
        result.setItems(items);
        return result;
    }

    @Override
    public PageResult<StudentListVO> getStudentWithMajorNamePage(int page, int size) {
        int p = Math.max(page, 1);
        int s = Math.max(size, 1);
        int offset = (p - 1) * s;
        List<StudentListVO> items = officeMapper.selectStudentsWithMajorNamePaged(offset, s);
        long total = officeMapper.countStudents();
        PageResult<StudentListVO> result = new PageResult<>();
        result.setPage(p);
        result.setSize(s);
        result.setTotal(total);
        result.setItems(items);
        return result;
    }

    @Override
    public PageResult<Counselor> getCounselorPage(int page, int size) {
        int p = Math.max(page, 1);
        int s = Math.max(size, 1);
        int offset = (p - 1) * s;
        List<Counselor> items = officeMapper.selectCounselorsPaged(offset, s);
        long total = officeMapper.countCounselors();
        PageResult<Counselor> result = new PageResult<>();
        result.setPage(p);
        result.setSize(s);
        result.setTotal(total);
        result.setItems(items);
        return result;
    }

    @Override
    public PageResult<CounselorWithMajorVO> getCounselorWithMajorPage(int page, int size) {
        int p = Math.max(page, 1);
        int s = Math.max(size, 1);
        int offset = (p - 1) * s;
        
        // 获取分页的辅导员列表
        List<Counselor> counselors = officeMapper.selectCounselorsPaged(offset, s);
        long total = officeMapper.countCounselors();
        
        // 转换为CounselorWithMajorVO
        List<CounselorWithMajorVO> items = counselors.stream().map(counselor -> {
            CounselorWithMajorVO vo = new CounselorWithMajorVO();
            vo.setId(counselor.getId());
            vo.setName(counselor.getName());
            vo.setFaculty(counselor.getFaculty());
            
            // 查询辅导员负责的专业ID列表
            List<CounselorMajor> counselorMajors = counselorMajorMapper.selectList(
                new QueryWrapper<CounselorMajor>().eq("counselor_id", counselor.getId())
            );
            List<Integer> majorIds = counselorMajors.stream()
                .map(CounselorMajor::getMajorId)
                .collect(Collectors.toList());
            vo.setMajorIds(majorIds);
            
            return vo;
        }).collect(Collectors.toList());
        
        PageResult<CounselorWithMajorVO> result = new PageResult<>();
        result.setPage(p);
        result.setSize(s);
        result.setTotal(total);
        result.setItems(items);
        return result;
    }

    @Override
    public Major createMajor(Major major) {
        // 创建专业
        majorMapper.insertMajor(major);
        return major;
    }

    @Override
    public Major getMajorByNameAndFacultyId(String majorName, Integer facultyId) {
        // 根据专业名字和学院ID查找专业
        return majorMapper.selectByNameAndFacultyId(majorName, facultyId);
    }

    @Override
    public boolean deleteFacultyById(Integer id) {
        // 删除学院前检查是否存在下属专业
        List<Major> majors = majorMapper.selectByFacultyId(id);
        if (majors != null && !majors.isEmpty()) {
            throw new IllegalStateException("无法删除学院，该学院下还有专业");
        }
        
        int result = facultyMapper.deleteFacultyById(id);
        return result > 0;
    }

    @Override
    public boolean deleteMajorById(Integer id) {
        // 删除专业前检查是否有学生使用该专业
        // 这里可以添加额外的业务检查逻辑
        
        int result = majorMapper.deleteMajorById(id);
        return result > 0;
    }

    @Override
    public boolean deleteCounselorById(Integer id) {
        // 删除辅导员前检查相关约束
        // 这里可以添加额外的业务检查逻辑
        
        int result = counselorMapper.deleteCounselorById(id);
        return result > 0;
    }
}